package rs.udd.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import rs.udd.exceptions.UddException;
import rs.udd.model.Category;
import rs.udd.repository.CategoryRepository;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

	@Resource
	private CategoryRepository categoryRepository;

	@Override
	public Category save(Category t) throws UddException {
		try {
			return categoryRepository.save(t);
		} catch (Exception e) {
			throw new UddException("Udd exception", e);
		}
	}

	@Override
	public void delete(Long id) throws UddException {
		try {
			categoryRepository.delete(id);
		} catch (Exception e) {
			throw new UddException("Udd exception", e);
		}
	}

	@Override
	public List<Category> findAll() throws UddException {
		try {
			return categoryRepository.findAll();
		} catch (Exception e) {
			throw new UddException("Udd exception", e);
		}
	}

	@Override
	public Category findCategoryByName(String name) throws UddException {
		try {
			return categoryRepository.findCategoryByName(name);
		} catch (Exception e) {
			throw new UddException("Udd exception", e);
		}
	}

	@Override
	public List<Category> findCategoryByNameLike(String name) {
		return categoryRepository.findCategoryByNameLike(name);
	}
	
	@Override
	public Category findOne(Long id) throws UddException {
		try {
			return categoryRepository.findOne(id);
		} catch (Exception e) {
			throw new UddException("Udd exception", e);
		}
	}

	@Override
	public List<Category> findAllForBrowse() throws UddException {
		try {
			List<Category> categories = categoryRepository.findAll();
			for (Category category : categories) {
				category.getAdverts().size();
			}
			return categories;
		} catch (Exception e) {
			throw new UddException("Udd exception", e);
		}
	}

	@Override
	public Category add(String newCategoryName) {
		Category existingCategory = categoryRepository.findCategoryByName(newCategoryName);
		if (existingCategory == null) {
			Category newCategory = new Category();
			newCategory.setName(newCategoryName);
			
			categoryRepository.save(newCategory);
			return newCategory;
		} else {
			return null;
		}
	}

}
